package com.edu.springboot_disk_erban.controller;

import com.edu.springboot_disk_erban.dao.FileDao;
import com.edu.springboot_disk_erban.entity.BaseFilePath;
import com.edu.springboot_disk_erban.entity.FileBean;
import com.edu.springboot_disk_erban.entity.ResultModel;
import com.edu.springboot_disk_erban.handler.HDFSHandler;
import com.edu.springboot_disk_erban.utils.HDFSConnectUtils;
import com.edu.springboot_disk_erban.utils.TimeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
public class HDFSController {

    @Resource
    HDFSHandler handler;

    @Resource
    FileDao filedao;
//    FileDao filedao = new FileDao();

    @Resource
    HDFSConnectUtils hdfsConnectUtils;

    /**
     * addFile?filename
     */
    @RequestMapping("/addFile")
    @ResponseBody
    public ResultModel<List<FileBean>> addDir(@RequestParam String filename) {
        FileBean byFilePath = filedao.findByFilePath(filename);
        ResultModel<List<FileBean>> resultModel;
        //filename = /zqp/歌曲
        if (byFilePath == null) {
            try {
                handler.addDir(filename);
                String realName = filename.substring(filename.lastIndexOf("/") + 1);
                System.out.println(realName);
                FileBean fileBean = new FileBean(realName, filename, "0", TimeUtils.getNowTime(), 1);
                filedao.addFileBean(fileBean);
                resultModel = ResultModel.success("添加成功");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            resultModel = ResultModel.error("添加失败！，文件名重复！");
        }
        return resultModel;

    }

    /**
     * upload
     */

    @RequestMapping("/upload")
    @ResponseBody

    public void upload(MultipartFile file, @RequestParam String filepath) throws IOException {
        handler.upload(file, filepath);
    }


    /**
     * lists
     */


    //basepath = /zqp
    //  /zqp/歌曲/周杰伦 ---> [,zqp,歌曲,周杰伦]
    // /zqp --->[,zqp]
    //想要的路径 /zqp/歌曲 ---->[,zqp,歌曲]
    //想要的路径 /zqp/电影 ----.
    // 想要的路径 /zqp/man.jpg
    @RequestMapping("/lists")
    @ResponseBody

    public ResultModel<List<FileBean>> getUserList(@RequestParam(defaultValue = "1") Integer pagenum, @RequestParam(defaultValue = "5") Integer pagesize, @RequestParam() String basepath) throws IOException {
        List<FileBean> bySonPath = filedao.findBySonPath(basepath);
        System.out.println("basepath=" + basepath);
        System.out.println(bySonPath);

        for (int i = 0; i < bySonPath.size(); i++) {
            //移除的就是多的哪一个
            String[] splits = bySonPath.get(i).getFilePath().split("/");
            System.out.println("+++++ " + Arrays.toString(splits));

            //移除
            if (splits.length != (basepath.split("/").length + 1)) {
                bySonPath.remove(bySonPath.get(i));
                System.out.println("----- " + Arrays.toString(splits));
                i--;
            }
        }
        int total = bySonPath.size();
        ResultModel<List<FileBean>> resultModel;
        if (bySonPath != null) {
            resultModel = ResultModel.success("查询列表成功", bySonPath,total);
        } else {
            resultModel = ResultModel.error("查询列表失败");
        }
        return resultModel;
    }

    /**
     * searchFiles?filePath
     */

    @RequestMapping("/searchFiles")
    @ResponseBody

    public ResultModel<List<FileBean>> getSearchFiles(@RequestParam String filePath) throws IOException {
        List<FileBean> sonFileDatas = filedao.findBySonPath(filePath);
        ResultModel<List<FileBean>> resultModel;
        for (int i = 0; i < sonFileDatas.size(); i++) {
            //移除的就是多的哪一个
            String[] splits = sonFileDatas.get(i).getFilePath().split("/");
            //移除
            if (splits.length != (filePath.split("/").length + 1)) {
                sonFileDatas.remove(sonFileDatas.get(i));
                i--;
            }
        }
        //创建集合
        ArrayList<BaseFilePath> baseFilePaths = new ArrayList<>();
        //处理路径
        String[] FileSplits = filePath.split("/");
        //定义一个全路径
        String abslutePath = "";
        for (int i = 1; i < FileSplits.length; i++) {
            //
            abslutePath += ("/" + FileSplits[i]);
            BaseFilePath baseFilePath = new BaseFilePath(FileSplits[i], abslutePath);
            baseFilePaths.add(baseFilePath);
        }

        if (sonFileDatas != null) {
            resultModel = ResultModel.success("查询列表成功！", sonFileDatas, baseFilePaths, sonFileDatas.size());
        } else {
            resultModel = ResultModel.error("查询列表失败！");
        }
        return resultModel;
    }

    /**
     * alterFiles 修改
     */

    @RequestMapping("/alterFiles")
    @ResponseBody
    public void alterFile(@RequestParam String filepath, @RequestParam String oldname, @RequestParam String newname) {
        String oldPath = filepath + "/" + oldname;
        String newPath = filepath + "/" + newname;

        handler.alterFile(oldPath, newPath);
    }

    /**
     * 假删除
     * deleteFiles?deleteFilepath
     */
    @RequestMapping("/deleteFiles")
    @ResponseBody
    public void deleteFiles(@RequestParam String deleteFilepath) {
        FileBean byFilePath = filedao.findByFilePath(deleteFilepath);
        System.out.println(byFilePath);
        filedao.addRubbishFile(byFilePath);
        filedao.deleteByPath(deleteFilepath);
    }
    /**
     * 还原
     */
    @RequestMapping("/restoreFiles")
    @ResponseBody
    public void restoreFiles(@RequestParam String deleteFilepath) {
        FileBean byFilePath = filedao.findRubbishByFilePath(deleteFilepath);
//        System.out.println(byFilePath);
        filedao.addFileBeanFile(byFilePath);
        filedao.deleteRubbishByPath(deleteFilepath);
    }
    /**
     * 获取回收站数据
     * rubbishListsFiles
     */
    @RequestMapping("/rubbishListsFiles")
    @ResponseBody
    public ResultModel<List<FileBean>> rubbishListsFiles(@RequestParam String filepath) {
        List<FileBean> rubbishAll = filedao.findRubbishBySonPath(filepath);

        ResultModel<List<FileBean>> resultModel;
        if (rubbishAll != null) {
            resultModel = ResultModel.success("查询列表成功！！！", rubbishAll, rubbishAll.size());
        } else {
            resultModel = ResultModel.error("查询列表失败！！！");
        }
        return resultModel;
    }

    /**
     * 收藏及取消收藏
     * collectFiles?filepath=filepath
     */
    @RequestMapping("/collectFiles")
    @ResponseBody
    public ResultModel<String> getCollectLists(String filepath) {
        ResultModel<String> resultModel;
        System.out.println(filepath);
        // 去collect表中查找这条数据是否存在
        FileBean collectFile = filedao.findByCollectPath(filepath);
        // 这条数据存在，返回给前端一个提示信息：该数据已存在，则从collect表中删除这条数据
        if (collectFile != null){
           filedao.delCollectFile(filepath);
           resultModel = ResultModel.success("取消收藏成功","0");
        }else {
            // 在fileBean表中查询到对应的该条要被收藏的数据
            FileBean byFilePath = filedao.findByFilePath(filepath);
            filedao.addCollectFile(byFilePath);
            resultModel = ResultModel.success("收藏成功","1");
        }
        return resultModel;



    }
    @RequestMapping("/cancelcollectFiles")
    @ResponseBody
    public void getCancelCollectLists(@RequestParam String filepath) {
        filedao.delCollectFile(filepath);
    }


    /**
     * collectionListsFiles?filepath
     */
    @RequestMapping("/collectionListsFiles")
    @ResponseBody
    public ResultModel<List<FileBean>> collectionListsFiles(@RequestParam String filepath) {
        List<FileBean> collectAll = filedao.findCollectBySonPath(filepath);

        //
        ResultModel<List<FileBean>> resultModel;
        if (collectAll != null) {
            resultModel = ResultModel.success("查询列表成功！！！", collectAll, collectAll.size());
        } else {
            resultModel = ResultModel.error("查询列表失败！！！");
        }
        return resultModel;
    }

    /**
     * 下载
     */
    @RequestMapping("/downLoadFile")
    @ResponseBody
    public String downLoadFile(@RequestParam String filePath) throws IOException {
        String url = hdfsConnectUtils.getHDFSNameNode() + "/webhdfs/v1" + filePath + "?op=OPEN";
        return url;

    }

    /**
     * 真正的删除功能
     */

    @RequestMapping("/deleteRubbishFiles")
    @ResponseBody
    public void deleteRubbishFiles(@RequestParam String deleteFilepath) {

        handler.deleteRubbishFiles(deleteFilepath);

        filedao.deleteByRubbishPath(deleteFilepath);

    }

    /**
     * *         searchFiles22?searchFilename=  搜索功能
     * */

    @RequestMapping("/searchFiles22")
    @ResponseBody
    public ResultModel<List<FileBean>> getLists(@RequestParam String searchFilename){
        List<FileBean> sonFileDatas = filedao.findSearchName(searchFilename);
        ResultModel<List<FileBean>> resultModel;
        if (sonFileDatas != null) {
            resultModel = ResultModel.success("查询列表成功！！！", sonFileDatas, sonFileDatas.size());
        } else {
            resultModel = ResultModel.error("查询列表失败！！！");
        }
        return resultModel;
    }
}
